package com.cheerscpl.loader;

import com.cheerscpl.TaskQueue;
import com.cheerscpl.service.TaskQueueService;
import com.cheerscpl.service.TaskService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Set;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;


/**
 * Created by chenpuliang on 2017/6/3.
 */
public class ExecutorsLoader implements InitializingBean {

    private static final Logger logger = LoggerFactory.getLogger(ExecutorsLoader.class);

    @Autowired
    private TaskService taskService;
    @Autowired
    private TaskQueueService taskQueueService;

    @Override
    public void afterPropertiesSet() throws Exception {
        taskQueueService.initQueue();
        ScheduledExecutorService executor = new ScheduledThreadPoolExecutor(
                Runtime.getRuntime().availableProcessors()+1);
        executor.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                try{
                    Set<TaskQueue> queues = taskQueueService.getQueueSet();
                    for(TaskQueue taskQueue : queues){
                        taskService.handleTasks(taskQueue);
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }, 0, 1, TimeUnit.SECONDS);
        logger.info("ExecutorsLoader startup success.");
    }
}
